package com.zzptc.sky.baidudemo.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.zzptc.sky.baidudemo.R;
import com.zzptc.sky.baidudemo.db.MobileInfoDao;
import com.zzptc.sky.baidudemo.vo.ContactsInfo;
import com.zzptc.sky.baidudemo.vo.ContactsInfo2;
import com.zzptc.sky.baidudemo.vo.MobileInfo;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/5/17 017 .
 */

public class MyUntils {
    public static boolean isHaveSDcard(){
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    //判断是否有外置存储卡
    public static File getDir(){
        File file;
        if (isHaveSDcard()){
            file = Environment.getExternalStorageDirectory();
        }else {
            file = Environment.getDownloadCacheDirectory();
            //file = Environment.getExternalStorageDirectory();
        }
        return file;
    }

    /**
     *
     * @param file 需要安装的File对象
     * @return
     */
    //获取安装意图
    public static Intent getInstallIntent(File file){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        return intent;
    }

    /**
     *
     * @param smdate 小的日期
     * @param bdate 大的日期
     * @return  返回差的天数
     * @throws ParseException
     */
    //计算2个日期差
    public static int daysBetween(Date smdate, Date bdate) throws ParseException
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    //获取当前版本号
    public static  int getVersionCode(Context context){
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(),0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static Drawable getBaiBoxIcon(String strPic){
        Context context = MyApplication.getContext();
        int resId = context.getResources().getIdentifier(strPic,"mipmap",context.getPackageName());
        Drawable drawable = ContextCompat.getDrawable(context,resId);
        return drawable;
    }

    /**
     *
     * @param context 上下文
     * @param dbname 原始文件名字
     * @throws IOException
     */
    //复制文件到手机
    public static void copyFileToMobile(Context context,String dbname) throws IOException {

        //url 原始文件的位置
        //目标File对象
        URL url = context.getClass().getClassLoader().getResource("assets/"+dbname);
        String dbpath = "/data/data/"+MyApplication.getContext().getPackageName()+"/databases";

        File file = new File(dbpath);
        if (!file.exists()){
            file.mkdir();
        }

        FileUtils.copyURLToFile(url,new File(file,dbname));
    }

    /**
     *
     * @param strNumber 需要判断的手机号码
     * @return
     */
    //判断号码是否符合手机号格式
    public static boolean isPhoneNumber(String strNumber){
        Pattern p = Pattern.compile("^((14[0-9])|(13[0-9])|(15[0-9])|(18[0-9])|(17[0-9]))\\d{8}$");
        Matcher m = p.matcher(strNumber);
        return m.matches();
    }

    //查询 需要添加读联系人权限  修改需要添加写联系人权限
    public static List<ContactsInfo> getAllContacts(){
        List<ContactsInfo> list = new ArrayList<ContactsInfo>();

        Uri raw_contactsUri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri dataUri = Uri.parse("content://com.android.contacts/data");

        ContentResolver contentResolver = MyApplication.getContext().getContentResolver();

        //根据raw_caontacts表获取联系人id
        Cursor csRaw = contentResolver.query(raw_contactsUri,null,null,null,null);
        //遍历cursor  获取联系人id 和姓名
        if (csRaw != null){
            //指针能移动到下一个 就有数据
            while (csRaw.moveToNext()){
                ContactsInfo contactsInfo = new ContactsInfo();
                //字段名 百度获得 或者导出手机数据库查看    获取每一个id
                String id = csRaw.getInt(csRaw.getColumnIndex("contact_id"))+"";

                //查询第二个表  获取第二个内筒提供者
                ContentResolver cr = MyApplication.getContext().getContentResolver();
                ////根据表一获取的联系人id，查询表二mimetype,data1  字段的数据
                Cursor cursorData = cr.query(dataUri,new String[]{"mimetype","data1"},"contact_id=?",new String[]{id},null);

                if (cursorData != null){
                    //如果 表二的数据不为空 就遍历
                    while (cursorData.moveToNext()){
                        //获取数据
                        String mimetype = cursorData.getString(0);  //数据对于的数据类型
                        String data = cursorData.getString(1);  //数据

                        //判断数据类型    数据类型在表三
                        //电话数据类型vnd.android.cursor.item/phone_v2
                        if (mimetype.equals("vnd.android.cursor.item/phone_v2")){  //是电话号码
                            contactsInfo.setPhone(data);

                        }else if ("vnd.android.cursor.item/email_v2".equals(mimetype)) {  //是邮箱

                        } else if ("vnd.android.cursor.item/name".equals(mimetype)) {  //是姓名
                            contactsInfo.setName(data);
                        }
                        contactsInfo.setId(id);
                    }
                     contactsInfo.setAddr(getAttributionByTel(contactsInfo.getPhone()));

                }else {
                    //表二为空
                }
                //关闭表二
                cursorData.close();
                list.add(contactsInfo);
            }
            csRaw.close();
        }else {
            //表一为空
        }

        return list;
    }

    //查询手机联系人
    public static List<ContactsInfo2> getAllContacts2(){
        List<ContactsInfo2> list = new ArrayList<ContactsInfo2>();
        //根据内容提供者查询
        ContentResolver contentResolver = MyApplication.getContext().getContentResolver();
        //查询联系人 URI  ContactsContract.Contacts.CONTENT_URI
        Cursor cursorID = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
        if (cursorID != null){
            while (cursorID.moveToNext()){
                //创建联系人对象
                ContactsInfo2 info = new ContactsInfo2();
                //id字段查询ID
                int id = cursorID.getInt(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
                //姓名字段查询姓名
                String name = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                //查询是否有电话号码
                int num = cursorID.getInt(cursorID.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                //大于0 说明有电话号码
                String phoneNumber = "";
                if (num > 0){
                    //根据id 在表二查询电话号码
                    //再一次获得一个内容提供者
                    ContentResolver cr = MyApplication.getContext().getContentResolver();
                    //电话号码uri  ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                    // 1.查询的URI     2.要查询的字段(null就是所有字段)        3.筛选条件      4.筛选值       5.是否排序
                    Cursor cs = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.Contacts._ID+"=?",new String[]{String.valueOf(id)},null);
                    //不为空 就说明有数据
                    if (cs != null){
                        //只取一个数据 就不用while
                        if (cs.moveToNext()){
                            //获取电话号码字段的值
                            phoneNumber = cs.getString(cs.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        }
                    }
                    cs.close();
                }
                //查询到电话号码  获取手机归属地
                //在全局Appliaction中复制外部数据到手机   初始化GreenDao
                //使用GreenDao操作外部数据库
                String addr = getAttributionByTel(phoneNumber);

                //添加数据
                info.setId(id);
                info.setName(name);
                info.setNumber(phoneNumber);
                info.setAddr(addr);

                //对象添加到集合
                list.add(info);
            }
            //记得关闭游标 ，不然指针会指向上一次的位置 而不是重头开始
            cursorID.close();
        }
        return list;
    }

    /**
     *
     * @param phoneNumber 需要查询的手机号码
     * @return 返回手机号码归属地
     */
    //根据手机号码 获取手机归属地
    public static String getAttributionByTel(String phoneNumber){
        //把传过的参数处理  去掉中间空格  去掉中间-    然后截取前7位

        //替换之前判断下是否有需要替换的字符
        //String tel = phoneNumber.replace(" ","").replace("-","").substring(0,7);
        if(phoneNumber.contains(" ")){
            phoneNumber = phoneNumber.replace(" ","");
        }
        if (phoneNumber.contains("-")){
            phoneNumber = phoneNumber.replace("-","");
        }

        //Caused by: java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=7
        String tel = phoneNumber.substring(0,7);

        //通过GreenDao根据电话号码查询数据
        MobileInfo mobileInfo = MyApplication.getMobileSession().getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.MobileNumber.eq(tel)).distinct().unique();
        return mobileInfo.getMobileArea();
    }

    /**
     *  可以查询手机号码和座机号码的归属地
     * @param phoneNumber  需要查询的的号码
     * @return 返回归属地
     */
    public static String getAttributionByTelNumber(String phoneNumber){
        //创建手机对象
        MobileInfo mobileInfo = null;
        //吧原始号码处理
        String reNumber = phoneNumber.replace(" ","").replace("-","");
        //根据号码长度 和 正则表达式 来判断是座机号码  还是手机号码
        if (reNumber.length() == 11 && reNumber.matches("^1[3578]\\d{9}$]")){
            //是手机号码
            //截取前7位
            mobileInfo = MyApplication.getMobileSession().getMobileInfoDao().queryBuilder()
                    .where(MobileInfoDao.Properties.MobileNumber.eq(reNumber.substring(0,7))).distinct().unique();
        }else {
            //是座机号码
            //根据原始号码长度 判断座机号码是那种情况
            //   区号+座机号     3+7     3+8     4+7     4+8
            switch (reNumber.length()){
                case 10:
                    // 3+7      是这种情况就截取前3位进行查询
                    mobileInfo = MyApplication.getMobileSession().getMobileInfoDao().queryBuilder()
                            .where(MobileInfoDao.Properties.AreaCode.eq(reNumber.substring(0,3))).limit(1).distinct().unique();
                    break;
                case 11:
                    //  3+8     4+7
                    mobileInfo = MyApplication.getMobileSession().getMobileInfoDao().queryBuilder()
                            .where(MobileInfoDao.Properties.AreaCode.eq(reNumber.substring(0,3))).limit(1).distinct().unique();
                    if (mobileInfo != null){
                        //如果3+8 没查到  就4+7   截取前4位进行查询
                        mobileInfo = MyApplication.getMobileSession().getMobileInfoDao().queryBuilder()
                                .where(MobileInfoDao.Properties.AreaCode.eq(reNumber.substring(0,4))).limit(1).distinct().unique();
                    }
                    break;
                case 12:
                    // 4+8  截取前4位进行查询
                    mobileInfo = MyApplication.getMobileSession().getMobileInfoDao().queryBuilder()
                            .where(MobileInfoDao.Properties.AreaCode.eq(reNumber.substring(0,4))).limit(1).distinct().unique();
                    break;
                default:
                    //上面情况都不是
                    if (mobileInfo == null){
                        mobileInfo = new MobileInfo();
                        mobileInfo.setMobileArea("未知号码");
                    }
            }
        }
        return mobileInfo.getMobileArea();
    }
}
